<?php
/**
 * Created by PhpStorm.
 * Date: 2018/8/17
 * Time: 上午10:00
 */

namespace app\common\model;
use think\facade\Cache;
use think\facade\Db;

/*************************************设置的KEY**************************************/

//网站设置
define("ZFN_SETTINGS_SYSTEM", "key_system");
//各种协议
define("ZFN_SETTINGS_AGREEMENT", "key_agreement");
//轮播
define("ZFN_SETTINGS_SWIPER", "key_swiper");
//信用卡
define("ZFN_SETTINGS_CREDIT", "key_credit");
//菜单导航
define("ZFN_SETTINGS_MENU", "key_menu");
//快递
define("ZFN_SETTINGS_EXPRESS", "key_express");
//支付成功广告
define("ZFN_SETTINGS_PAY_AD", "key_pay_ad");
//退款原因
define("ZFN_SETTINGS_ORDER_REASON", "key_order_reason");
//海报
define("ZFN_SETTINGS_POSTER", "key_poster");
//会员等级设置
define("ZFN_SETTINGS_USER_LEVEL", "key_user_level");
//会员团队等级设置
define("ZFN_SETTINGS_USER_TEAM_LEVEL", "key_user_team_level");
//会员分销商等级设置
define("ZFN_SETTINGS_USER_DIS_LEVEL", "key_user_dis_level");
//代理等级设置
define("ZFN_SETTINGS_AGENT_LEVEL", "key_agent_level");
//经纪人等级设置
define("ZFN_SETTINGS_BROKER_LEVEL", "key_broker_level");
//门店等级设置
define("ZFN_SETTINGS_STORE_LEVEL", "key_store_level");
//商家等级设置
define("ZFN_SETTINGS_MERCH_LEVEL", "key_merch_level");

class Settings extends Base
{
    /**
     * 获取指定的设置
     *
     * @param $key
     * @param $type 1 缓存存到 system_settings 2 按key单独
     * @return mixed|null
     */
    public static function getSettings($key)
    {
        //初始化设置值
        $settings = null;

        if (Cache::store("redis")->has($key))
        {
            //获取缓存
            $settings = Cache::store("redis")->get($key);
        }

        //如果没有缓存
        if (is_null($settings))
        {
            //从数据库中检索数据
            $item = Db::name("system_settings")
                ->where("key_name", $key)
                ->find();

            //如果设置为空
            if (empty($item) || empty($item["value"]))
            {
                $settings = array();
            }
            else
            {
                //反串行化
                $settings = unserialize($item["value"]);

                Cache::store("redis")->set($key, $settings);
            }
        }

        return $settings;

    }

    /**
     * 设置系统设置值
     * @param $key
     * @param $value
     * @return bool|int|string
     */
    static public function setSettings($key, $value)
    {
        //设置结果
        $result = false;

        //获取item
        $item = Db::name("system_settings")
            ->where("key_name", $key)
            ->find();

        //如果存在设置项，则更新值
        if ($item)
        {
            $result = Db::name("system_settings")
                ->where("key_name", $key)
                ->update(["value"=>serialize($value)]);
        }
        //否则创建设置
        else
        {
            $result = Db::name("system_settings")
                ->insert(array(
                    "key_name" => $key,
                    "value" => serialize($value),
                ));
        }

        Cache::store("redis")->set($key, $value);

        return $result;
    }

    /**
     * 保存配置参数
     */
    static public function saveSystem(){
        //查找所有系统设置表数据
        $system = [];
        $info = System::getListField()->toArray();
        //格式化设置字段
        $info = sysgem_setup($info);
        foreach ($info as $k => $v) {
            $system[$v['field']] = $v['value'];
        }

        Cache::store("redis")->set(ZFN_SETTINGS_SYSTEM,$system);
        return $system;
    }

    /**
     * 获取参数
     * @param string $field 参数名
     * @return array|false|mixed|\PDOStatement|string|Model
     */
    static public function getSystem($field=''){
        $system = Cache::store("redis")->get(ZFN_SETTINGS_SYSTEM);
        if(empty($system)){
            $system = self::saveSystem();
        }
        if(empty($field)){
            return $system;
        }else{
            return $system[$field];
        }
    }


    /**
     * 保存海报配置参数
     */
    static public function savePoster(){

        $poster = Db::name('poster')
            ->order('sort DESC,id DESC')
            ->column('id,type,title,status,data','id');
        foreach ($poster as &$item) {
            $item['data'] = unserialize($item['data']);
        }
        unset($item);
        Cache::store("redis")->set(ZFN_SETTINGS_POSTER,$poster);
        return $poster;
    }

    /**
     * 获取海报
     */
    static public function getPoster($key=''){
        $poster = Cache::store("redis")->get(ZFN_SETTINGS_POSTER);
        if(empty($poster)){
            $poster = self::savePoster();
        }
        if(empty($key)){
            return $poster;
        }else{
            return @$poster[$key];
        }
    }

    /**
     * 保存协议
     */
    static public function saveAgreement(){
        $agreement = Db::name('agreement')
            ->column('id,key,title,content','id');
        Cache::store("redis")->set(ZFN_SETTINGS_AGREEMENT,$agreement);
        return $agreement;
    }

    /**
     * 获取协议
     */
    static public function getAgreement($id=''){
        $agreement = Cache::store("redis")->get(ZFN_SETTINGS_AGREEMENT);
        if(empty($agreement)){
            $agreement = self::saveAgreement();
        }
        if(empty($id)){
            return $agreement;
        }else{
            return $agreement[$id];
        }
    }

    /**
     * 保存快递参数
     */
    static public function saveExpress(){
        $list = Db::name('express')
            ->order('sort DESC,id DESC')
            ->column('id,title,status,express,mobile','id');
        $list = empty($list)?[]:$list;
        self::setSettings(ZFN_SETTINGS_EXPRESS,$list);
        return $list;
    }


    /**
     * 轮播保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveSwiper(){

        $list = get_swiper_type();
        $arr = [];
        foreach ($list as $item){
            $data = Db::name('swiper')
                ->where('type',$item['type'])
                ->where('status',1)
                ->field('img_url,link_type,link_url,link_data,link_other_type,mini_link_type,mini_link,mini_data,mini_other_type')
                ->order('sort desc,id desc')
                ->select()
                ->toArray();
            $data = empty($data)?[]:$data;

            foreach ($data as &$val){
                $val['img_url'] = manageImg($val['img_url']);
            }
            unset($val);

            $arr[$item['type']] = $data;
        }
        self::setSettings(ZFN_SETTINGS_SWIPER,$arr);
    }

    /**
     * 保存信用卡
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveCredit(){
        $data = Db::name('credit')
            ->where('status',1)
            ->field('title,img_url,link_type,link_url,link_data,link_other_type,mini_link_type,mini_link,mini_data,mini_other_type,description')
            ->order('sort desc,id desc')
            ->select()
            ->toArray();
        $data = empty($data)?[]:$data;

        foreach ($data as &$val){
            $val['img_url'] = manageImg($val['img_url']);
        }
        unset($val);
        self::setSettings(ZFN_SETTINGS_CREDIT,$data);
    }

    /**
     * 保存菜单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveMenu(){
        $list = get_menu_type();
        $arr = [];
        foreach ($list as $item){
            $data = Db::name('menu')
                ->where('type',$item['type'])
                ->where('status',1)
                ->field('title,img_url,link_type,link_url,link_data,link_other_type,mini_link_type,mini_link,mini_data,mini_other_type')
                ->order('sort desc,id desc')
                ->limit($item['limit'])
                ->select()
                ->toArray();
            $data = empty($data)?[]:$data;

            foreach ($data as &$val){
                $val['img_url'] = manageImg($val['img_url']);
            }
            unset($val);

            $arr[$item['type']] = $data;
        }
        self::setSettings(ZFN_SETTINGS_MENU,$arr);
    }

    /**
     * 订单退款原因保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveOrderReason(){
        $arr = Db::name('order_reason')
            ->where('status','=',1)
            ->order('sort DESC')
            ->column('id,title','id');
        self::setSettings(ZFN_SETTINGS_ORDER_REASON,$arr);
    }


    /**
     * 支付成功广告保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function savePayAd(){
        $arr = Db::name('pay_ad')
            ->column('status,thumb,link_type,link_url,link_data,link_other_type,
            mini_link_type,mini_link,mini_data,mini_other_type','id');
        foreach ($arr as &$item){
            $item['thumb'] = manageImg($item['thumb']);
            unset($item['id']);
        }
        unset($item);
        self::setSettings(ZFN_SETTINGS_PAY_AD,$arr);
    }

    /**
     * 会员等级保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveUserLevel(){
        $arr = Db::name('user_level')
            ->column('*','level_id');
        foreach ($arr as &$item){
            $item['interests'] = json_decode($item['interests'],true);
        }
        unset($item);
        self::setSettings(ZFN_SETTINGS_USER_LEVEL,$arr);
    }

    /**
     * 代理等级保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveAgentLevel(){
        $arr = Db::name('agent_level')
            ->column('*','id');
        self::setSettings(ZFN_SETTINGS_AGENT_LEVEL,$arr);
    }

    /**
     * 会员团队等级
     * @return void
     */
    static public function saveUserTeamLevel(){
        $arr = Db::name('user_team_level')
            ->column('*','id');
        self::setSettings(ZFN_SETTINGS_USER_TEAM_LEVEL,$arr);
    }

    /**
     * 会员分销商等级
     * @return void
     */
    static public function saveUserDisLevel(){
        $arr = Db::name('user_distributor_level')
            ->column('*','id');
        self::setSettings(ZFN_SETTINGS_USER_DIS_LEVEL,$arr);
    }

    /**
     * 经纪人等级保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveBrokerLevel(){
        $arr = Db::name('broker_level')
            ->order('id DESC')
            ->column('*','id');
        self::setSettings(ZFN_SETTINGS_BROKER_LEVEL,$arr);
    }

    /**
     * 门店等级保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveStoreLevel(){
        $arr = Db::name('store_level')
            ->order('id DESC')
            ->column('*','id');
        self::setSettings(ZFN_SETTINGS_STORE_LEVEL,$arr);
    }

    /**
     * 商家等级保存到缓存
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static public function saveMerchLevel(){
        $arr = Db::name('merch_level')
            ->column('*','id');
        foreach ($arr as &$item){
            $item['interests'] = json_decode($item['interests'],true);
        }
        unset($item);
        self::setSettings(ZFN_SETTINGS_MERCH_LEVEL,$arr);
    }
}
